<template>
	<el-dialog
		:visible.sync="visible"
		title="高级查询"
		:close-on-click-modal="false"
		class="global-dialog global-dialog_center superQuery-dialog"
		lock-scroll
		width="800px"
	>
		<div
			v-loading="loading"
			class="superQuery-main"
		>
			<template v-if="conditionList.length">
				<div class="matchLogic">
					<span>匹配逻辑：</span>
					<el-select
						v-model="matchLogic"
						:placeholder="t('请选择')"
					>
						<el-option
							label="AND(所有条件都要求匹配)"
							value="AND"
						/>
						<el-option
							label="OR(条件中的任意一个匹配)"
							value="OR"
						/>
					</el-select>
				</div>
				<div>
					<template v-for="(item, index) in conditionList">
						<el-row
							:key="index"
							class="condition-list"
							:gutter="20"
						>
							<el-col :span="8">
								<el-select
									v-model="item.model"
									placeholder="请选择查询字段"
									filterable
									clearable
									@change="onFieldChange($event, item, index)"
								>
									<el-option
										v-for="item in fieldOptions"
										:key="item.model"
										:label="item.config.label"
										:value="item.model"
									/>
								</el-select>
							</el-col>
							<el-col :span="4">
								<el-select
									v-model="item.symbol"
									:placeholder="t('请选择')"
								>
									<el-option
										v-for="item in symbolOptions"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									/>
								</el-select>
							</el-col>
							<el-col :span="8">
								<template v-if="item.identity === 'numInput'">
									<el-input-number
										v-model="item.value"
										:placeholder="t('请输入')"
										:precision="item.attr.precision"
										controls-position="right"
										style="width: 100%"
									/>
								</template>
								<template v-else-if="item.identity === 'calculate'">
									<el-input-number
										v-model="item.value"
										:placeholder="t('请输入')"
										controls-position="right"
										style="width: 100%"
										:precision="item.attr.precision || 0"
									/>
								</template>
								<template v-else-if="['rate', 'slider'].includes(item.identity)">
									<el-input-number
										v-model="item.value"
										:placeholder="t('请输入')"
										controls-position="right"
										style="width: 100%"
									/>
								</template>
								<div
									v-else-if="item.identity === 'switch'"
									style="padding-top: 5px"
								>
									<el-switch
										v-model="item.value"
										:active-value="1"
										:inactive-value="0"
									/>
								</div>
								<template v-else-if="item.identity === 'time'">
									<el-time-picker
										v-model="item.value"
										style="width: 100%"
										:picker-options="item.attr['picker-options']"
										:placeholder="t('请选择')"
										clearable
										:value-format="item.attr['value-format']"
										:format="item.attr.format"
									/>
								</template>
								<template
									v-else-if="
										['date', 'createTime', 'modifyTime'].includes(item.identity)
									"
								>
									<el-date-picker
										v-model="item.value"
										clearable
										:placeholder="t('请选择')"
										:type="
											item.identity === 'date' && item.attr.type
												? item.attr.type
												: 'datetime'
										"
										:value-format="item.attr['value-format']"
										style="width: 100%"
										:format="item.attr.format || 'yyyy-MM-dd HH:mm:ss'"
									/>
								</template>
								<template
									v-else-if="
										['comSelect', 'currOrganize'].includes(item.identity)
									"
								>
									<McComSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
									/>
								</template>
								<template v-else-if="['depSelect'].includes(item.identity)">
									<McDepSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
										:select-type="item.attr.selectType"
										:able-dep-ids="item.attr.ableDepIds"
									/>
								</template>
								<template
									v-else-if="['createUser', 'modifyUser'].includes(item.identity)"
								>
									<McUserSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
									/>
								</template>
								<template v-else-if="['userSelect'].includes(item.identity)">
									<McUserSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
										:select-type="
											item.attr.selectType != 'all' ||
												item.attr.selectType != 'custom'
												? 'all'
												: item.attr.selectType
										"
										:able-dep-ids="item.attr.ableDepIds"
										:able-pos-ids="item.attr.ablePosIds"
										:able-user-ids="item.attr.ableUserIds"
										:able-role-ids="item.attr.ableRoleIds"
										:able-group-ids="item.attr.ableGroupIds"
									/>
								</template>
								<template v-else-if="['usersSelect'].includes(item.identity)">
									<McUsersSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
										:select-type="item.attr.selectType"
										:able-ids="item.attr.ableIds"
									/>
								</template>
								<template v-else-if="['currPosition'].includes(item.identity)">
									<McPosSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
									/>
								</template>
								<template v-else-if="['posSelect'].includes(item.identity)">
									<McPosSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
										:select-type="item.attr.selectType"
										:able-dep-ids="item.attr.ableDepIds"
										:able-pos-ids="item.attr.ablePosIds"
									/>
								</template>
								<template v-else-if="item.identity === 'groupSelect'">
									<McGroupSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
									/>
								</template>
								<template v-else-if="item.identity === 'roleSelect'">
									<McRoleSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
									/>
								</template>
								<template v-else-if="item.identity === 'address'">
									<McAddress
										v-model="item.value"
										:placeholder="t('请选择')"
										:level="item.attr.level"
										clearable
									/>
								</template>
								<template
									v-else-if="
										['select', 'radio', 'checkbox'].includes(item.identity)
									"
								>
									<el-select
										v-model="item.value"
										:placeholder="t('请选择')"
										clearable
										filterable
									>
										<el-option
											v-for="(oItem, i) in item.attr.options"
											:key="i"
											:label="oItem[item.attr.props.props.label]"
											:value="oItem[item.attr.props.props.value]"
										/>
									</el-select>
								</template>
								<template v-else-if="item.identity === 'cascader'">
									<el-cascader
										v-model="item.value"
										:options="item.attr.options"
										clearable
										:show-all-levels="item.attr['show-all-levels']"
										:props="item.attr.props.props"
										filterable
										:placeholder="t('请选择')"
										style="width: 100%"
									/>
								</template>
								<template v-else-if="item.identity === 'treeSelect'">
									<mc-tree-select
										v-model="item.value"
										:placeholder="t('请选择')"
										:options="item.attr.options"
										:props="item.attr.props.props"
										clearable
									/>
								</template>
								<template v-else-if="item.identity === 'relationForm'">
									<relationForm
										v-model="item.value"
										:placeholder="t('请选择')"
										:model-id="item.attr.modelId"
										clearable
										:column-options="item.attr.columnOptions"
										:relation-model="item.attr.relationField"
										:has-page="item.attr.hasPage"
										:page-size="item.attr.pageSize"
									/>
								</template>
								<template v-else-if="item.identity === 'popupSelect'">
									<McPopupSelect
										v-model="item.value"
										:placeholder="t('请选择')"
										:interface-id="item.attr.interfaceId"
										clearable
										:column-options="item.attr.columnOptions"
										:props-value="item.attr.propsValue"
										:relation-model="item.attr.relationField"
										:has-page="item.attr.hasPage"
										:page-size="item.attr.pageSize"
										:popup-type="item.attr.popupType"
										:popup-title="item.attr.popupTitle"
										:popup-width="item.attr.popupWidth"
									/>
								</template>
								<template v-else-if="item.identity === 'popupTableSelect'">
									<McPopupTableSelect
										v-model="item.value"
										:placeholder="item.attr.placeholder"
										:interface-id="item.attr.interfaceId"
										:column-options="item.attr.columnOptions"
										:props-value="item.attr.propsValue"
										:relation-model="item.attr.relationField"
										:has-page="item.attr.hasPage"
										:page-size="item.attr.pageSize"
										:popup-type="item.attr.popupType"
										:popup-title="item.attr.popupTitle"
										:popup-width="item.attr.popupWidth"
										:filterable="item.attr.filterable"
										clearable
									/>
								</template>
								<template v-else-if="item.identity === 'autoComplete'">
									<McAutoComplete
										v-model="item.value"
										:placeholder="item.attr.placeholder"
										:interface-id="item.attr.interfaceId"
										:template-json="item.attr.templateJson"
										:total="item.attr.total"
										:relation-model="item.attr.relationField"
										clearable
									/>
								</template>
								<template v-else>
									<el-input
										v-model="item.value"
										:placeholder="t('请输入')"
										clearable
									/>
								</template>
							</el-col>
							<el-col :span="4">
								<el-button
									icon="el-icon-plus"
									@click="addCondition"
								/>
								<el-button
									icon="el-icon-minus"
									@click="delCondition(index)"
								/>
							</el-col>
						</el-row>
					</template>
				</div>
			</template>
			<div
				v-else
				class="query-noData"
			>
				<el-empty/>
				<div class="noData-txt">
					<span>没有任何查询条件</span>
					<el-divider direction="vertical"/>
					<el-link
						type="primary"
						:underline="false"
						@click="addCondition"
					>
						点击新增
					</el-link>
				</div>
			</div>
		</div>
		<template #footer>
			<span
				class="dialog-footer"
			>
				<div class="footer-options">
					<!-- <el-button
            class="add-btn"
            @click="addPlan"
          >保存方案</el-button>
          <el-popover
            ref="planPopper"
            width="240"
            trigger="click"
            popper-class="plan-popper"
          >
            <template #reference>
              <el-button>方案选择<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
            </template>
            <div
              v-if="planList.length"
              class="plan-list"
            >
              <div
                v-for="(item, i) in planList"
                :key="i"
                class="plan-list-item"
                @click="selectPlan(item)"
              >
                <el-link
                  type="primary"
                  :underline="false"
                  class="plan-list-name"
                >{{ item.fullName }}
                </el-link>
                <i
                  class="el-icon-close"
                  @click.stop="delPlan(item.id, i)"
                />
              </div>
            </div>
            <div
              v-else
              class="noData-txt"
            >{{ t("暂无数据") }}</div>
          </el-popover> -->
				</div>
				<el-button @click="visible = false">{{t("取消")}}</el-button>
				<el-button
					type="primary"
					:loading="btnLoading"
					@click="handleQuery"
				>查 询</el-button>
			</span>
		</template>
		<el-dialog
			:visible.sync="addPlanVisible"
			title="保存方案"
			width="600px"
			:append-to-body="true"
			lock-scroll
			class="global-dialog global-dialog_center"
		>
			<el-form
				ref="dataForm"
				:model="dataForm"
				:rules="dataRule"
				label-width="80px"
			>
				<el-form-item
					label="方案名称"
					prop="fullName"
				>
					<el-input
						v-model="dataForm.fullName"
						placeholder="请输入保存的方案名称"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<span
					class="dialog-footer"
				>
					<el-button @click="addPlanVisible = false">{{t("取消")}}</el-button>
					<el-button
						type="primary"
						:loading="saveBtnLoading"
						@click="savePlan()"
					>
						{{t("确定")}}</el-button>
				</span>
			</template>
		</el-dialog>
	</el-dialog>
</template>

<script>
import {dyOptionsList} from '../../utils/config.js';
import {t} from '../../utils/index.js';
/* ⬇️ 未迁移功能 ⬇️*/
// import { getAdvancedQueryList, Delete, Create, Update } from '@/api/system/advancedQuery';
// import { getDictionaryDataSelector } from '@/api/systemData/dictionary';
// import { getDataInterfaceRes } from '@/api/systemData/dataInterface';
export default {
	props:{
		columnOptions:{
			type:Array,
			default:() => [],
		},
	},
	data(){
		return {
			t,
			visible:false,
			addPlanVisible:false,
			loading:false,
			btnLoading:false,
			saveBtnLoading:false,
			matchLogic:'AND',
			conditionList:[
				{
					model:'',
					value:'',
					symbol:'EQ',
					identity:'',
					attr:{},
				},
			],
			key2:+new Date(),
			planList:[],
			fieldOptions:[],
			symbolOptions:[
				{
					label:'大于等于',
					value:'GE',
				},
				{
					label:'大于',
					value:'GT',
				},
				{
					label:'等于',
					value:'EQ',
				},
				{
					label:'小于等于',
					value:'LE',
				},
				{
					label:'小于',
					value:'LT',
				},
				{
					label:'不等于',
					value:'NE',
				},
				{
					label:'包含',
					value:'LK',
				},
				{
					label:'不包含',
					value:'NL',
				},
			],
			dataForm:{
				fullName:'',
			},
			dataRule:{
				fullName:[{required:true, message:'请输入保存的方案名称', trigger:'blur'}],
			},
		};
	},
	computed:{
		currMenuId(){
			return this.$route.meta.modelId || '';
		},
	},
	methods:{
		init(){
			this.visible = true;
			this.loading = true;
			const componentList = JSON.parse(JSON.stringify(this.columnOptions));
			this.fieldOptions = componentList;
			this.getAdvancedQueryList();
			this.$nextTick(() => {
				this.loading = false;
			});
		},
		buildOptions(componentList){
			componentList.forEach((cur) => {
				const config = cur.config;
				if(config.identity === 'cascader') cur.props.props.multiple = false;
				if(dyOptionsList.indexOf(config.identity) > -1){
					if(config.dataType === 'dictionary'){
						if(!config.dictionaryType) return;
            // getDictionaryDataSelector(config.dictionaryType).then((res) => {
            //   cur.options = res.data.list;
            // });
					}
					if(config.dataType === 'dynamic'){
						if(!config.propsUrl) return;
            // getDataInterfaceRes(config.propsUrl).then((res) => {
            //   const data = res.data;
            //   if (Array.isArray(data)) {
            //     cur.options = data;
            //   } else {
            //     cur.options = [];
            //   }
            // });
					}
				}
			});
			return componentList;
		},
		getAdvancedQueryList(){
			if(!this.currMenuId) return;
    //   getAdvancedQueryList(this.currMenuId).then((res) => {
    //     this.planList = res.data.list;
    //   });
		},
		onFieldChange(val, item, i){
			if(!val){
				item.identity = '';
				item.value = undefined;
				item.attr = {};
				return;
			}
			const obj = this.columnOptions.filter((o) => o.model === val)[0];
			item.identity = obj.config.identity;
			item.attr = obj;
			if(item.identity === 'cascader') item.attr.props.props.multiple = false;
			const config = item.attr.config;
			if(dyOptionsList.indexOf(config.identity) > -1){
				if(config.dataType === 'dictionary'){
					if(!config.dictionaryType) return;
        //   getDictionaryDataSelector(config.dictionaryType).then((res) => {
        //     item.attr.options = res.data.list;
        //   });
				}
				if(config.dataType === 'dynamic'){
					if(!config.propsUrl) return;
        //   getDataInterfaceRes(config.propsUrl).then((res) => {
        //     const data = res.data;
        //     if (Array.isArray(data)) {
        //       item.attr.options = data;
        //     } else {
        //       item.attr.options = [];
        //     }
        //   });
				}
			}
			item.value = undefined;
			this.$set(this.conditionList, i, item);
		},
		addCondition(){
			const item = {
				model:'',
				value:'',
				symbol:'EQ',
				identity:'',
				attr:{},
			};
			this.conditionList.push(item);
		},
		delCondition(index){
			this.conditionList.splice(index, 1);
		},
		delPlan(id, i){
    //   Delete(id).then((res) => {
    //     this.$message({
    //       type: 'success',
    //       message: res.msg,
    //       duration: 1500,
    //       onClose: () => {
    //         this.planList.splice(i, 1);
    //       },
    //     });
    //   });
		},
		selectPlan(item){
			this.matchLogic = item.matchLogic;
			this.conditionList = item.condition || [];
			this.$refs.planPopper.doClose();
		},
		addPlan(){
			if(!this.conditionList.length) return this.$message.warning('请添加条件');
			if(!this.exist()) return;
			this.addPlanVisible = true;
			this.$nextTick(() => {
				this.$refs['dataForm'].resetFields();
			});
		},
		savePlan(){
			this.$refs['dataForm'].validate((valid) => {
				if(valid){
					const boo = this.planList.some((o) => o.fullName === this.dataForm.fullName);
					if(!boo) return this.submit();
					const list = this.planList.filter((o) => o.fullName === this.dataForm.fullName);
					this.$confirm(`${list[0].fullName}已存在, 是否覆盖方案?`, '', {
						type:'warning',
					})
						.then(() => {
							this.submit(list[0].id);
						})
						.catch(() => {});
				}
			});
		},
		submit(id){
			this.saveBtnLoading = true;
			const query = {
				id:id || '',
				...this.dataForm,
				matchLogic:this.matchLogic,
				moduleId:this.currMenuId,
				condition:this.conditionList,
			};
    //   const formMethod = query.id ? Update : Create;
    //   formMethod(query)
    //     .then((res) => {
    //       this.getAdvancedQueryList();
    //       this.addPlanVisible = false;
    //       this.saveBtnLoading = false;
    //       this.$message({
    //         message: res.msg,
    //         type: 'success',
    //         duration: 1500,
    //       });
    //     })
    //     .catch(() => {
    //       this.saveBtnLoading = false;
    //     });
		},
		getDataType(identity){
			if(!identity) return '';
			if(['numInput', 'date', 'rate', 'slider'].includes(identity)){
				return 'number';
			}else if(
				['uploadFz', 'uploadImg', 'cascader', 'comSelect', 'address'].includes(identity)
			){
				return 'array';
			}
			return '';
		},
		exist(type){
			let isOk = true;
			for(let i = 0; i < this.conditionList.length; i++){
				const e = this.conditionList[i];
				if(!e.model){
					this.$message({
						message:`请选择查询字段`,
						type:'error',
						duration:1000,
					});
					isOk = false;
					break;
				}
				let flag = false;
				if(this.getDataType(e.identity) === 'array'){
					flag = this.$commonUtils.isEmptyArray(e.value);
				}else{
					flag = this.$commonUtils.isEmpty(e.value);
				}
				if(flag){
					const mes = type === 'query' ? '查询' : '保存';
					this.$message({
						message:`空条件不能${mes}`,
						type:'error',
						duration:1000,
					});
					isOk = false;
					break;
				}
			}
			return isOk;
		},
		handleQuery(){
			if(!this.exist('query')) return;
			const query = {
				matchLogic:this.matchLogic,
				condition:this.conditionList,
			};
			this.visible = false;
			this.$emit('super-query', query);
		},
	},
};
</script>
<style lang="scss" scoped>
.superQuery-dialog {
    ::v-deep .el-dialog {
        .el-dialog__body {
            padding: 20px 20px 10px 24px;
        }
        .footer-options {
            float: left;
            .add-btn {
                margin-right: 10px;
            }
        }
    }
    .superQuery-main {
        .query-noData {
            text-align: center;
            padding: 20px 0;
            .noData-img {
                width: 160px;
                margin-bottom: 10px;
            }
            .noData-txt {
                color: #909399;
            }
        }
        .matchLogic {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            line-height: 32px;
            .el-select {
                width: 220px;
            }
        }
        .condition-list {
            margin-bottom: 10px;
        }
    }
}
</style>
<style lang="scss">
.plan-popper {
    padding: 0 !important;
    .plan-list {
        padding: 6px 0;
        max-height: 182px;
        overflow: auto;
        &-item {
            height: 34px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #606266;
            font-size: 14px;
            cursor: pointer;
            padding: 0 20px;
            &:hover {
                background-color: #f5f7fa;
            }
        }
        .plan-list-name {
            .el-link--inner {
                width: 160px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }
        .el-icon-close:hover {
            color: #f56c6c;
        }
    }
    .noData-txt {
        height: 34px;
        color: #999;
        font-size: 14px;
        line-height: 34px;
        text-align: center;
    }
}
</style>